<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/26 0026
 * Time: 11:33
 */

namespace app\admin\controller;


use app\admin\model\Expert;
use app\admin\model\ExpertCategory;
use app\admin\model\Member;
use think\Db;
use php\Slpic;
use OSS\OssClient;
use OSS\Core\OssException;

class Jborder extends Base
{

    //获取线上订单列表
    public function onlists()
    {
        if (isset($this->_param['op']) && $this->_param['op'] == 'table') {

            if(isset($this->_param['status'])&&$this->_param['status']==10)
            {
                unset($this->_map['status']);
            }

            $where = $this->_map;
            unset($where['page']);
            unset($where['op']);
            unset($where['limit']);

            $list = Db::table('mxkj_identify_order')
//                ->join('mxkj_expert_category', 'mxkj_identify_order.category_id = mxkj_expert_category.id')
//                ->join('mxkj_expert', 'mxkj_expert.uid=mxkj_identify_order.expert_uid')
//                ->field('mxkj_expert.name as e_name')
                ->field('mxkj_identify_order.*')
                ->where($where)
//                ->field('mxkj_expert_category.name as c_name')
                ->order('mxkj_identify_order.id desc');
            $t_list = clone ($list);
            $total = $t_list->count();
            $list->limit(($this->_param['page'] - 1) * $this->_param['limit'], $this->_param['limit']);

            $_list = clone($list);
            $total = $list->count();//print_r(Db::name('member')->getLastSql());die;
            $list = $_list;
            $list->limit(($this->_param['page']-1)*$this->_param['limit'],$this->_param['limit']);
            $data = $list->select();
            $this->assign('map', $this->_param);

            $new_list = [];
            foreach ($data as $k => $v) {
                $user = Member::get(['id' => $v['uid']]);
                $exp = Expert::get(['uid' => $v['expert_uid']]);
                $cate=ExpertCategory::get(['id' => $v['category_id']]);
                $v['c_name'] = $cate['name'];
                $v['e_name'] = $exp['name'];
                $v['nickname'] = $user['nickname'];
                $v['create_time'] = $v['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : '';
                $v['pay_time'] = $v['pay_time'] ? date('Y-m-d H:i:s', $v['pay_time']) : '';
                $v['finish_time'] = $v['finish_time'] ? date('Y-m-d H:i:s', $v['finish_time']) : '';
                //检查是否有追加
                $add_ques = db('identify_order_add')->where('order_id', $v['id'])->find();
                $v['add_num'] = empty($add_ques) ? 0 : 1;
                $new_list[] = $v;
            }
            $this->ajaxReturn('', $new_list, $total);
        }
        if (!isset($this->_param['op'])) {
            return $this->fetch('Jborder/onlists');
        }
    }

    //获取订单详情
    public function show_info($order_id)
    {
        $url = $this->url;
        $info = Db::table('mxkj_identify_order')->where('mxkj_identify_order.id', $order_id)
            ->join('mxkj_expert_category', 'mxkj_identify_order.category_id = mxkj_expert_category.id')
            ->join('mxkj_expert', 'mxkj_expert.uid=mxkj_identify_order.expert_uid')
            ->field('mxkj_expert.name as e_name')
            ->field('mxkj_identify_order.*')
            ->field('mxkj_expert_category.name as c_name')
            ->order('mxkj_identify_order.id desc')->find();

        $user = Member::get(['id' => $info['uid']]);
        $exp = Member::get(['id' => $info['expert_uid']]);
        $info['nickname'] = $user['nickname'];
        $info['u_mobile'] = $user['mobile'];
        $info['e_mobile'] = $exp['mobile'];
        $info['create_time'] = $info['create_time'] ? date('Y-m-d H:i:s', $info['create_time']) : '';
        $info['pay_time'] = $info['pay_time'] ? date('Y-m-d H:i:s', $info['pay_time']) : '';
        $info['finish_time'] = $info['finish_time'] ? date('Y-m-d H:i:s', $info['finish_time']) : '';

        $jiaobao = $this->onjianbao();
        $jieguyo = $this->jieguyo();
        $info['str_status'] = $jiaobao[$info['status']];
        $info['result_flag'] = $jieguyo[$info['result_flag']];
        $info['is_urgent'] = $info['is_urgent'] ? '加急' : '普通';

        $info['img'] = $url . '/uploads/teasure/' . $info['img'];
        $img_list_str = "";
        if (!empty($info['detail_imgs']) || $info['detail_imgs'] != '') {
            $newstr = substr($info['detail_imgs'], 0, strlen($info['detail_imgs']) - 1);
            if (!empty($newstr) && $newstr != "") {
                $d['imgs'] = explode(",", $newstr);
                foreach ($d['imgs'] as $v) {
                    $img_list_str .= $url . '/uploads/teasure/' . $v . ",";
                }
                $info['detail_imgs'] = $img_list_str;
            }
        }

        $this->assign('info', $info);

        return $this->fetch('Jborder/info');
    }

    //获取追加的问题列表
    public function add_list()
    {
        if (isset($this->_param['op']) && $this->_param['op'] == 'table') {
            $list = db('identify_order_add')->order('id desc');
            $total = $list->count();
            $list->limit(($this->_param['page'] - 1) * $this->_param['limit'], $this->_param['limit']);
            $where = $this->_param;
            unset($where['page']);
            unset($where['op']);
            unset($where['limit']);
            (!empty($where)) ? $data = $list->where('order_id', $this->_param['order_id'])->select() : $data = $list->where('order_id', $this->_param['order_id'])->select();
            $this->assign('map', $this->_param);
            foreach ($data as $k => $v) {
                $d = time() - $data[$k]['create_time'];
                $data[$k]['create_time'] = $data[$k]['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : '';
                $data[$k]['update_time'] = $data[$k]['update_time'] ? date('Y-m-d H:i:s', $v['update_time']) : '';

            }
            $this->ajaxReturn('', $data, $total);
        }
        if (!isset($this->_param['op'])) {
            $this->assign('order_id', $this->_param['order_id']);
            return $this->fetch('Jborder/add_list');
        }
    }

    //取消订单
    public function cancel_order()
    {
        $order = db('identify_order')->where('status', 0)->where('id', $this->_param['order_id'])->find();
        if (empty($order)) $this->response("订单状态不存在", 201);

        Db::name('identify_order')->where('id', $this->_param['order_id'])->update(['status' => -1]);

        $this->ajaxReturn("取消成功", 200);

    }

    //删除订单
    public function del_order()
    {
        $order = db('identify_order')->where('status=-1 or status=-2')->where('id', $this->_param['order_id'])->find();
        if (empty($order)) $this->response("订单状态不存在", 201);

        Db::name('identify_order')->delete($order);

        $this->ajaxReturn("删除成功", 200);

    }

    //鉴宝类别管理
    public function category()
    {
        $url = $this->url;
        if (isset($this->_param['op']) && $this->_param['op'] == 'table') {
            $list = db('expert_category')->order('id desc');
            $total = $list->count();
            $list->limit(($this->_param['page'] - 1) * $this->_param['limit'], $this->_param['limit']);
            $where = $this->_param;
            unset($where['page']);
            unset($where['op']);
            unset($where['limit']);
            (!empty($where)) ? $data = $list->order('id desc')->select() : $data = $list->order('id desc')->select();
            $this->assign('map', $this->_param);
            foreach ($data as $k => $v) {
                $data[$k]['cate_img'] = $url . '/uploads/teasure/' . $v['cate_img'];
                $data[$k]['str_status'] =  $data[$k]['status']?'正常':'禁用' ;
            }
            $this->ajaxReturn('', $data, $total);
        }
        if (!isset($this->_param['op'])) {
            return $this->fetch('Jborder/category');
        }
    }

    //添加类别
    public function add_cate()
    {
        return $this->fetch('Jborder/add_cate');
    }

    //添加类别操作
    public function adding_cate()
    {
        $temp = Db::name('expert_category')->insert($this->_param);
        if ($temp) {
            $this->success('添加成功!');
        } else {
            $this->success('添加失败!');
        }
    }

    //编辑类别
    public function edit_cate($id)
    {
        $url = $this->url;
        $cate = \db('expert_category')->where('id', $id)->find();
        $cate['cate_img'] = $url . '/uploads/teasure/' . $cate['cate_img'];

        $this->assign('cate', $cate);
        return $this->fetch('Jborder/add_cate');
    }

    public function editing_cate()
    {
        $temp = Db::name('expert_category')->update($this->_param);
        if ($temp) {
            $this->success('编辑成功!');
        } else {
            $this->success('编辑失败!');
        }
    }

    //禁用
    public function disable()
    {
        $cate=Db::name('expert_category')->where('id',$this->_param['id'])->find();
        $this->_param['status']=$cate['status']?0:1;
        $temp = Db::name('expert_category')->update($this->_param);
        if ($temp) {
            $this->success('编辑成功!');
        } else {
            $this->success('编辑失败!');
        }
    }

//    //上传图片
//    public function upload_img()
//    {
//        if (!empty($_FILES['uploadkey'])) {
//            $new_dir = isset($new_dir) ? $new_dir : $_SERVER['DOCUMENT_ROOT'] . '/uploads/teasure';
//            if (!file_exists($new_dir)) {
//                $this->createDir($new_dir);
//            }
//            $file = $_FILES['uploadkey'];
//
//            $tmp_file = $file ['tmp_name'];
//            $file_types = explode(".", $file['name']);
//            $file_type = $file_types [count($file_types) - 1];
//            $file_names = substr(md5(rand(1, time())), rand(0, 8), 20) . '.' . $file_type;
//            $file_name = $new_dir . '/' . $file_names;
//
//            //$this->response('图片上传失败222',200,$file_name);
//            if (!in_array(strtolower($file_type), array('gif', 'png', 'jpg'))) {
//                $this->ajaxReturn('不是要求图片文件，请重新选择！', 201);
//                exit();
//            }
//            //$this->response('图片上传失败222',200,$new_dir);
//            if (file_exists($file_name)) {
//                @unlink($file_name);
//            }
//
//            $pic = new Slpic(array('file' => $tmp_file));
//            $pic->resize(300, 300);
//            $result = $pic->save($file_name, $file_type);
//            //$this->response('图片上传失败222',200,$new_dir);
//            if ($result) {
//
//                $this->ajaxReturn('修改成功', 200, $file_names);
//            } else {
//                $this->ajaxReturn('图片上传失败', 201);
//            }
//
//            /*//等比压缩为知道尺寸
//            $this->load->library('slpic', array('file' => $tmp_file));
//            $this->slpic->resize(150, 50);
//            $result = $this->slpic->save($new_dir . $file_name, $file_type);*/
//
//        } else {
//            $this->ajaxReturn('图片上传失败', 201, $_FILES);
//        }
//    }

    function upload()
    {
        $path = '/uploads/teasure/';
        // 获取表单上传文件 例如上传了001.jpg
//        $file = request()->file('file');
        // 移动到框架应用根目录/public/uploads/ 目录下
        //$info = $file->rule('uniqid')->move(ROOT_PATH . 'public' . DS . 'uploads/teasure');

        foreach ($_FILES as $name => $file) {
            $file_types = explode(".", $file['name']);
            $file_type = $file_types [count($file_types) - 1];
            $fn = substr(md5(rand(1, time())), rand(0, 8), 20) . '.' . $file_type;
            $ft = strrpos($fn, '.', 0);
            $fm = substr($fn, 0, $ft);
            $fe = substr($fn, $ft);
            $fp = $_SERVER['DOCUMENT_ROOT'] . $path . $fn;
            $fi = 1;

            if (!in_array(strtolower($file_type), array('gif', 'png', 'jpg', 'jpeg'))) {
                $this->ajaxReturn('格式不对', 201);
            }

            while (file_exists($fp)) {
                $fn = $fm . '[' . $fi . ']' . $fe;
                $fp = $_SERVER['DOCUMENT_ROOT'] . $path . $fn;;
                $fi++;
            }

            $result = move_uploaded_file($file['tmp_name'], $fp);
        }

        if ($result) {

            //上传阿里云OSS
            if(true)
            {
                $root = $_SERVER['DOCUMENT_ROOT'];
                if (is_file($root . '/../extend/oss/autoload.php')) {
                    require_once $root . '/../extend/oss/autoload.php';
                }
                $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
                try {
                    $ossClient->uploadFile($this->bucket, substr($path,1).$fn, $fp);
                    unlink($fp);
                } catch (OssException $e) {
                    printf($e->getMessage() . "\n");
                    return;
                }
            }

            $this->ajaxReturn('修改成功', 200, $fn);
        } else {
            // 上传失败返回错误信息
            $this->ajaxReturn('图片上传失败', 201);
        }
    }

    //线下订单
    public function under_order()
    {

        if (isset($this->_param['op']) && $this->_param['op'] == 'table') {

            if(isset($this->_param['status'])&&$this->_param['status']==10)
            {
                unset($this->_map['status']);
            }

            $where = $this->_map;
            unset($where['page']);
            unset($where['op']);
            unset($where['limit']);

            $list = Db::table('mxkj_identify_order_unline')
//                ->join('mxkj_expert_category', 'mxkj_identify_order.category_id = mxkj_expert_category.id')
//                ->join('mxkj_expert', 'mxkj_expert.uid=mxkj_identify_order.expert_uid')
//                ->field('mxkj_expert.name as e_name')
                ->field('mxkj_identify_order_unline.*')
                ->where($where)
//                ->field('mxkj_expert_category.name as c_name')
                ->order('mxkj_identify_order_unline.id desc');
            $t_list = clone ($list);
            $total = $t_list->count();
            $list->limit(($this->_param['page'] - 1) * $this->_param['limit'], $this->_param['limit']);

            $_list = clone($list);
            $total = $list->count();//print_r(Db::name('member')->getLastSql());die;
            $list = $_list;
            $list->limit(($this->_param['page']-1)*$this->_param['limit'],$this->_param['limit']);
            $data = $list->select();
            $this->assign('map', $this->_param);

            $new_list = [];
            foreach ($data as $k => $v) {
                $user = Member::get(['id' => $v['uid']]);
                $exp = Expert::get(['uid' => $v['expert_uid']]);
//                $cate=ExpertCategory::get(['id' => $v['category_id']]);
//                $v['c_name'] = $cate['name'];
                $v['e_name'] = $exp['name'];
                $v['nickname'] = $user['nickname'];
                $v['create_time'] = $v['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : '';
                $v['pay_time'] = $v['pay_time'] ? date('Y-m-d H:i:s', $v['pay_time']) : '';
                $v['finish_time'] = $v['finish_time'] ? date('Y-m-d H:i:s', $v['finish_time']) : '';
                //检查是否有追加
                $add_ques = db('identify_order_add')->where('order_id', $v['id'])->find();
                $v['add_num'] = empty($add_ques) ? 0 : 1;
                $new_list[] = $v;
            }
            $this->ajaxReturn('', $new_list, $total);
        }
        if (!isset($this->_param['op'])) {
            return $this->fetch('Jborder/under_order');
        }

//        if (isset($this->_param['op']) && $this->_param['op'] == 'table') {
//            $list = Db::table('mxkj_identify_order_unline')
//                ->join('mxkj_expert', 'mxkj_expert.uid=mxkj_identify_order_unline.expert_uid')
//                ->field('mxkj_expert.name as e_name')
//                ->field('mxkj_identify_order_unline.*')
//                ->order('mxkj_identify_order_unline.id desc');
//            $t_list = clone ($list);
//            $total = $t_list->count();
//            $list->limit(($this->_param['page'] - 1) * $this->_param['limit'], $this->_param['limit']);
//            $where = $this->_map;
//            unset($where['page']);
//            unset($where['op']);
//            unset($where['limit']);
//            (!empty($where)) ? $data = $list->whereor($where)->select() : $data = $list->select();
//            $this->assign('map', $this->_param);
//            $new_list = [];
//            foreach ($data as $k => $v) {
//                $user = Member::get(['id' => $v['uid']]);
//                $v['nickname'] = $user['nickname'];
//                $v['create_time'] = $v['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : '';
//                $v['pay_time'] = $v['pay_time'] ? date('Y-m-d H:i:s', $v['pay_time']) : '';
//                $v['finish_time'] = $v['finish_time'] ? date('Y-m-d H:i:s', $v['finish_time']) : '';
//                //检查是否有追加
//                $add_ques = db('identify_order_add')->where('order_id', $v['id'])->find();
//                $v['add_num'] = empty($add_ques) ? 0 : 1;
//                $new_list[] = $v;
//            }
//            $this->ajaxReturn('', $new_list, $total);
//        }
//        if (!isset($this->_param['op'])) {
//            return $this->fetch('Jborder/under_order');
//        }
    }

    //取消订单 代付款 和预约中 和已预约 都能取消
    public function cancel_un_order()
    {
        $uid = $this->_param['uid'];
        $user = \app\api\model\Member::get(['id' => $uid]);
        $order = db('identify_order_unline')->where('uid', $uid)->where('id', $this->_param['order_id'])->find();

        //代付款
        if ($order['status'] == 0) {
            Db::name('identify_order_unline')->where('id', $this->_param['order_id'])->update(['status' => -1]);
            $this->ajaxReturn("取消成功", 200);
        } //预约中
        else if ($order['status'] == 1) {
            Db::startTrans();
            try {
                Db::name('identify_order_unline')->where('id', $this->_param['order_id'])->update(['status' => -1]);
                $count = $order['price'];
                $data['lcc_wallet'] = $user['lcc_wallet'] + $count;
                db('member')->where('id', $uid)->update($data);
                add_bill($uid, $count, 2, 3);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->ajaxReturn("取消失败", 201);
            }
            $this->ajaxReturn("取消成功", 200);
        } //已预约
        else if ($order['status'] == 2) {
            Db::startTrans();
            try {
                Db::name('identify_order_unline')->where('id', $this->_param['order_id'])->update(['status' => -1]);
                $count = $order['price'];
                $data['lcc_wallet'] = $user['lcc_wallet'] + $count;
                db('member')->where('id', $uid)->update($data);
                add_bill($uid, $count, 2, 3);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->ajaxReturn("取消失败", 201);
            }
            $this->ajaxReturn("取消成功", 200);
        } else {
            $this->ajaxReturn("订单状态不存在", 201);
        }

    }

    //删除订单
    public function del_un_order()
    {
        $order = db('identify_order_unline')->where('status=-1 or status=-2')->where('id', $this->_param['order_id'])->find();
        if (empty($order)) $this->ajaxReturn("订单状态不存在", 201);
        Db::name('identify_order_unline')->delete($order);
        $this->ajaxReturn("删除成功", 200);
    }

    //线下订单
    public function under_info($order_id)
    {
        $url = $this->url;
        $info = Db::table('mxkj_identify_order_unline')->where('mxkj_identify_order_unline.id', $order_id)
            ->join('mxkj_expert', 'mxkj_expert.uid=mxkj_identify_order_unline.expert_uid')
            ->field('mxkj_expert.name as e_name')
            ->field('mxkj_identify_order_unline.*')
            ->order('mxkj_identify_order_unline.id desc')->find();

        $user = Member::get(['id' => $info['uid']]);
        $exp = Member::get(['id' => $info['expert_uid']]);
        $info['nickname'] = $user['nickname'];
        $info['u_mobile'] = $user['mobile'];
        $info['e_mobile'] = $exp['mobile'];
        $info['create_time'] = $info['create_time'] ? date('Y-m-d H:i:s', $info['create_time']) : '';
        $info['pay_time'] = $info['pay_time'] ? date('Y-m-d H:i:s', $info['pay_time']) : '';
        $info['finish_time'] = $info['finish_time'] ? date('Y-m-d H:i:s', $info['finish_time']) : '';

        $jiaobao = $this->onjianbao();
        $jieguyo = $this->jieguyo();
        $info['str_status'] = $jiaobao[$info['status']];
        $info['result_flag'] = $jieguyo[$info['result_flag']];
        $this->assign('info', $info);
        return $this->fetch('Jborder/under_info');

    }


}
